package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.SQLPageDoing;
import com.rockcent.mall.lib.domain.enumclass.RecommandStatus;
import com.rockcent.mall.lib.dto.RecommendDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created by zhangjh on 2016/11/8.
 */
@Repository
public class RecommendRepositoryImpl implements RecommendRepositoryCustom {

    private static final Logger log = LoggerFactory.getLogger(RecommendRepositoryImpl.class);

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 推荐商家列表
     *
     * @param mallId
     * @return
     */
    @Override
    public PageResult<RecommendDto> getRecommendPageByMallId(Long mallId, String merchantName, String isRecommend, PageResult pageResult) {
        SQLPageDoing<RecommendDto> doing = (sql, fields, params, typeReferenceMap) -> {

            sql.append("SELECT %s FROM merchant m");
            sql.append(" WHERE m.`is_delete`='NO'");
            sql.append(" AND m.`mall_id`=:mallId");
            params.put("mallId", mallId);
            if (StringUtils.isNotBlank(isRecommend)) {
                if (RecommandStatus.valueOf(isRecommend) == RecommandStatus.YES) {
                    sql.append(" AND m.`id` in(SELECT merchant_id FROM recommend where is_delete='NO')");
                } else if (RecommandStatus.valueOf(isRecommend) == RecommandStatus.NO) {
                    sql.append(" AND m.`id` not in (SELECT merchant_id FROM recommend where is_delete='NO')");
                }
            }
            if (merchantName != null && !"".equals(merchantName)) {
                sql.append(" AND m.`name` like :merchantName");
                params.put("merchantName", "%" + merchantName + "%");
            }
            sql.append(" AND m.STATUS IN ('VERIFIED','DEVERIFY','PROBATION','DISABLED','NORMAL')");


            fields.append(" m.`id` as merchantId ,m.name AS merchantName,m.`intro`,CASE WHEN m.id  IN(SELECT merchant_id FROM recommend where is_delete='NO') THEN 'YES' ELSE 'NO'END as isRecommend");

        };
        return doing.go(pageResult, RecommendDto.class, objectMapper, jdbcTemplate, log);
    }
}